package main

import (
	"context"
	"fmt"
	"log"
	"net/http"
	"os"
	signal2 "os/signal"
	"strconv"
	"syscall"
	"time"
)

var ctx context.Context
var cancel context.CancelFunc

// 接收终端信号退出程序
func init() {
	ctx, cancel = context.WithCancel(context.Background())
}

func ListenSignal() {
	c := make(chan os.Signal)
	signal2.Notify(c, syscall.SIGINT, syscall.SIGTERM)
	for {
		select {
		case sig := <-c:
			fmt.Printf("receive signal %d\n", sig)
			cancel()
			return
		}
	}
}

func Index(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "%s", time.Now())
}

func CronJob() {
	ticker := time.NewTicker(1 * time.Second)
	for {
		select {
		case <-ticker.C:
			log.Println("cron working ...")
		case <-ctx.Done():
			log.Println("stopping cron ...")
			return
		}
	}
}

func ListenHttp(port int) {
	server := &http.Server{Addr: ":" + strconv.Itoa(port), Handler: nil}
	go func() {
		for {
			select {
			case <-ctx.Done():
				server.Close()
				return
			}
		}
	}()
	http.HandleFunc("/", Index)
	server.ListenAndServe() // 阻塞运行
	fmt.Printf("stop service on port %d\n", port)
}

func main() {
	go ListenHttp(8080)
	go ListenSignal()
	go CronJob()
	time.Sleep(60 * time.Second)
}
